/*
 * @lc app=leetcode.cn id=103 lang=cpp
 *
 * [103] 二叉树的锯齿形层序遍历
 */

#include <limits.h>

#include <iostream>
#include <map>
#include <queue>
#include <set>
#include <stack>
#include <vector>
using namespace std;

struct TreeNode {
    int val;
    TreeNode *left;
    TreeNode *right;
    TreeNode() : val(0), left(nullptr), right(nullptr) {}
    TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
    TreeNode(int x, TreeNode *left, TreeNode *right)
        : val(x), left(left), right(right) {}
};

// @lc code=start
/**
 * Definition for a binary tree node.
 * struct TreeNode {
 *     int val;
 *     TreeNode *left;
 *     TreeNode *right;
 *     TreeNode() : val(0), left(nullptr), right(nullptr) {}
 *     TreeNode(int x) : val(x), left(nullptr), right(nullptr) {}
 *     TreeNode(int x, TreeNode *left, TreeNode *right) : val(x), left(left),
 * right(right) {}
 * };
 */
class Solution {
   public:
    vector<vector<int>> zigzagLevelOrder(TreeNode *root) {
        int order = 0;  // 记录遍历顺序，0为自左向右，1为自右向左
        vector<int> layer;             // 记录每一层的节点值
        vector<vector<int>> result;    // 记录最终的结果
        stack<TreeNode *> nodeStack0;  // 记录自左向右待访问的节点
        stack<TreeNode *> nodeStack1;  // 记录自右向左待访问的节点

        // 根节点为空，直接返回
        if (root == nullptr) return result;

        // BFS like
        nodeStack0.push(root);
        while (!nodeStack0.empty() || !nodeStack1.empty()) {
            if (order == 0) {
                // 自左向右遍历节点
                while (!nodeStack0.empty()) {
                    TreeNode *node = nodeStack0.top();
                    nodeStack0.pop();

                    layer.push_back(node->val);

                    if (node->left != nullptr) nodeStack1.push(node->left);
                    if (node->right != nullptr) nodeStack1.push(node->right);
                }
                // 将该层的节点放入最终结果，并交换遍历顺序
                result.push_back(layer);
                layer.clear();
                order = 1 - order;
            } else {
                // 自右向左遍历节点
                while (!nodeStack1.empty()) {
                    TreeNode *node = nodeStack1.top();
                    nodeStack1.pop();

                    layer.push_back(node->val);

                    if (node->right != nullptr) nodeStack0.push(node->right);
                    if (node->left != nullptr) nodeStack0.push(node->left);
                }
                // 将该层的节点放入最终结果，并交换遍历顺序
                result.push_back(layer);
                layer.clear();
                order = 1 - order;
            }
        }

        return result;
    }
};
// @lc code=end
